﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Web;
using System.Net;
using System.IO.Compression;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;

namespace BaccaratRally.WinnerClient
{
    public partial class Form1 : Form
    {
        public List<DateTime> LastChangedTime;
        public List<DateTime> LastSetTime;
        public List<Byte> StatusList;
        public List<Bitmap> PicList;
        public int BlockWidth;


        public Form1()
        {
            InitializeComponent();

            BlockWidth = 36;
            this.wbMain.Navigate("http://www.wh966.com");

            this.wbMain.AllowWebBrowserDrop = false;
            ((SHDocVw.DWebBrowserEvents_Event)wbMain.ActiveXInstance).NewWindow += wbMain_NewWindow;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (this.btnStart.Text == "开始")
            {
                this.btnStart.Text = "暂停";
                LastSetTime = new List<DateTime>() { DateTime.Now.AddSeconds(-20), DateTime.Now.AddSeconds(-20), DateTime.Now.AddSeconds(-20), DateTime.Now.AddSeconds(-20) };
                LastChangedTime = new List<DateTime>() { DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now };
                StatusList = new List<byte>() { 1,1,1,1 };

                PicList = new List<Bitmap>() { };
                PicList.Add(GetStatusPic(1));
                PicList.Add(GetStatusPic(2));
                PicList.Add(GetStatusPic(3));
                PicList.Add(GetStatusPic(4));
                this.TopMost = true;
                this.timerMain.Enabled = true;
                this.timerMain.Start();
            }
            else
            {
                this.timerMain.Stop();
                this.TopMost = false;
                this.btnStart.Text = "开始";
            }
        }

        private void timerMain_Tick(object sender, EventArgs e)
        {
            timerMain.Stop();

            for (int i = 1; i < 5; i++)
            {
                Bitmap pic = GetStatusPic(i);
                if (ImageComparison(pic, PicList[i-1]) < 1)
                {
                    if (StatusList[i - 1] == 2 && LastSetTime[i - 1] < DateTime.Now.AddSeconds(-30))
                    {
                        DateTime ltime = LastSetTime[0];
                        if (LastSetTime[1] > ltime) ltime = LastSetTime[1];
                        if (LastSetTime[2] > ltime) ltime = LastSetTime[2];
                        if (LastSetTime[3] > ltime) ltime = LastSetTime[3];

                        if (ltime < DateTime.Now.AddSeconds(-4))
                        {
                            SetBet(i);
                            LastSetTime[i - 1] = DateTime.Now;
                            StatusList[i - 1] = 1;
                        }
                    }

                    if (LastSetTime[i - 1] < DateTime.Now.AddSeconds(-40) && StatusList[i - 1] == 1)
                    {
                        ClickBet(i);
                        StatusList[i - 1] = 2;
                    }

                    LastChangedTime[i - 1] = DateTime.Now;
                    PicList[i - 1] = pic;
                }
            }

            timerMain.Start();
        }

        private Bitmap GetStatusPic(int tableno)
        {
            int x = 640;
            int y = 146 + (tableno - 1) * 174;

            Bitmap pic = new Bitmap(BlockWidth, BlockWidth, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Graphics g1 = Graphics.FromImage(pic);
            g1.CopyFromScreen(new Point(this.Location.X + x, this.Location.Y + y), new Point(0, 0), new Size(BlockWidth, BlockWidth));

            g1.Dispose();
            return pic;
        }

        private void ClickBet(int tableno)
        {
            Random sizeRandom = new Random(Guid.NewGuid().GetHashCode());
            double sizeRandomDigital = sizeRandom.NextDouble();

            int basesize = 100;
            if (sizeRandomDigital > 0.8) basesize += 10;
            if (sizeRandomDigital > 0.85) basesize += 10;
            if (sizeRandomDigital > 0.9) basesize += 10;
            if (sizeRandomDigital > 0.95) basesize += 10;

            Random directionRandom = new Random(Guid.NewGuid().GetHashCode());
            double directionRandomDigital = sizeRandom.NextDouble();

            string direction = "B";

            if (directionRandomDigital > double.Parse(this.txbDirection.Text))
            {
                direction = "V";
            }

            ClickAction(tableno, basesize, direction);
            Console.WriteLine("click action " + tableno.ToString() +" size:" + basesize.ToString() + " direction:" + direction );
        }

        private void ClickAction(int tableno, int size, String direction)
        {
            int chipy = 394;

            int tx = 907;
            int hx = 1011;

            int x = 0;
            int y = 0;

            if (direction == "B")
            {
                x = 842;
                y = 161 + (tableno - 1) * 174;
            }
            if (direction == "V")
            {
                x = 718;
                y = 161 + (tableno - 1) * 174;
            }
            if (direction == "D")
            {
                x = 733;
                y = 228 + (tableno - 1) * 174;
            }

            SetCursorPos(hx + this.Location.X, chipy + this.Location.Y);
            mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
            mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);
            Thread.Sleep(500);
            Application.DoEvents();


            SetCursorPos(x + this.Location.X, y + this.Location.Y);
            mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
            mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);
            Thread.Sleep(500);
            Application.DoEvents();

            if (size > 100)
            {
                SetCursorPos(tx + this.Location.X, chipy + this.Location.Y);
                mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
                mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);
                
                Thread.Sleep(500);
                Application.DoEvents();

                SetCursorPos(x + this.Location.X, y + this.Location.Y);
                mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
                mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);
                Thread.Sleep(500);
                Application.DoEvents();

                if (size > 110)
                {
                    mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
                    mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);
                }
                if (size > 120)
                {
                    mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
                    mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);
                }
                if (size > 130)
                {
                    mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
                    mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);
                }
            }
        }

        private void SetBet(int tableno)
        {
            int x = 780;
            int y = 262 + (tableno - 1) * 174;

            SetCursorPos(x + this.Location.X, y + this.Location.Y);
            mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
            mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);
        }

        #region Base Func for Click & Window
        public float ImageComparison(Bitmap img1, Bitmap img2)
        {
            if (img1.Width == img2.Width && img1.Height == img2.Height && img1.Width != 0 && img1.Height != 0)
            {
                int equalCount = 0;

                for (int i = 0; i < img1.Width; i++)
                {
                    for (int j = 0; j < img1.Height; j++)
                    {
                        if (img1.GetPixel(i, j) == img2.GetPixel(i, j))
                        {
                            equalCount++;
                        }
                    }
                }

                return (float)equalCount / (img1.Width * img1.Height);
            }
            else
            {
                return 0;
            }
        }

        public void wbMain_NewWindow(string url, int flag, string target, ref object data, string header, ref bool processed)
        {
            processed = true;
            wbMain.Navigate(url);
        }

        /// <summary>
        /// 这部分是控制鼠标定位的基础类和方法，不用管，已经封装好了。
        /// </summary>
        #region Mouse Base Action
        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);
        [Flags]
        enum MouseEventFlag : uint
        {
            Move = 0x0001,
            LeftDown = 0x0002,
            LeftUp = 0x0004,
            RightDown = 0x0008,
            RightUp = 0x0010,
            MiddleDown = 0x0020,
            MiddleUp = 0x0040,
            XDown = 0x0080,
            XUp = 0x0100,
            Wheel = 0x0800,
            VirtualDesk = 0x4000,
            Absolute = 0x8000
        }

        [DllImport("user32.dll")]
        static extern void mouse_event(MouseEventFlag flags, int dx, int dy, int cButtons, int dwExtraInfo);
        #endregion

        #endregion
    }
}
